package com.ruoyi.common.utils.security;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：zhanghao
 * @name：SignUtils
 * @Date：2024/7/16 17:46
 */
public class SignUtils {

    public static void main(String[] args) throws IOException {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_key","34704814");
        paramMap.put("method","taobao.tbk.tpwd.create");
        paramMap.put("v","2.0");
        paramMap.put("timestamp","2024-07-17+16:33:29");
        paramMap.put("partner_id","top-apitools");
        paramMap.put("format","json");
        paramMap.put("sign_method","md5");
        paramMap.put("url","https%3A%2F%2Fs.click.taobao.com%2Ft%3Fe%3Dm%3D2%26s%3DLbU%2B7%2BVYjrdw4vFB6t2Z2ueEDrYVVa64Dne87AjQPk9yINtkUhsv0BIZ%2BllkIhNWZPkAVTbxTM5Gez8RJHF2RoL82xAr7TFnH4LMiAXPNOHRVLlVqDkPzlmMDsQdQUYggvUNyyJS1KL3%2BWMkG3VUsygxCc9dRM7XeXELkYz6Rowg0OHTNTbQqPwB%2FMmQa7ZP%2FWbkkD0oIIDOQIvqBTFYYUzvUkvTqpJ7dy8hMxNR2N9WVL4P8UuC5PTZMyyW2%2BVQ5UkNt69qoNlMdIp1rr4P3Q%3D%3D%26scm%3D1007.15281.84132.0%26pvid%3Dc7aa70b0-cc42-413b-835a-49b99f59fc59%26app_pvid%3D59590_33.5.117.135_999_1721202763345%26ptl%3DfloorId%3A3786%3BoriginalFloorId%3A3786%3Bpvid%3Ac7aa70b0-cc42-413b-835a-49b99f59fc59%3Bapp_pvid%3A59590_33.5.117.135_999_1721202763345%26union_lens%3DlensId%3AMAPI%401721202763%4021057587_132b_190bfade6a3_6f22%4001%40eyJmbG9vcklkIjozNzg2fQieie");
        String info = signTopRequest(paramMap, "af7394bfd052a1024906c5271ab48b87", "md5");
        System.out.println(info);
    }

    public static boolean areNotEmpty(String[] values) {
        boolean result = true;
        if ((values == null) || (values.length == 0))
            result = false;
        else {
            for (String value : values) {
                result &= !StringUtils.isEmpty(value);
            }
        }
        return result;
    }


    public static String signTopRequest(Map<String, Object> params, String secret, String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (Constants.SIGN_METHOD_MD5.equals(signMethod)) { //签名的摘要算法，可选值为：hmac，md5，hmac-sha256
            query.append(secret);
        }
        for (String key : keys) {
//            System.out.println(key);
            String value = params.get(key).toString();
            if (areNotEmpty(new String[]{key, value})) {
//                System.out.println(key+"="+value);
                query.append(key).append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        if (Constants.SIGN_METHOD_HMAC.equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), secret);
        } else {
            query.append(secret);
            bytes = encryptMD5(query.toString());
        }

        // 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串，此方法需要时使用)
        return byte2hex(bytes);
    }

    public static byte[] encryptHMAC(String data, String secret) throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes(Constants.CHARSET_UTF8));
    }

    public static byte[] encryptMD5(byte[] data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data);
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

}
